<?php
/* ******************************
 *	Product Catalog aJax actions
 * ******************************
 */

set_time_limit(0);

include('../../includes/classes/core.php');
include('../../includes/classes/category.tree.class.php');

$action		= $_REQUEST['act'];
$error		= '';
$data		= '';
$user_id	= $_SESSION['USERID'];


switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);

        break;
    case 'get_edit_page':
	    $prod_id	= $_REQUEST['id'];
		$page		= GetPage(GetProduct($prod_id));

        $data 		= array('page'	=> $page);

        break;
        
   case 'save_identiti':
       $num=mysql_num_rows(mysql_query("SELECT *
                    FROM printer_identity
                    WHERE actived=1 AND `production_id`=$_REQUEST[printer_model] AND `parts_type`=$_REQUEST[part_type] AND `parts_category`=$_REQUEST[category]"));
       
       if ($num<1) {
           if($_REQUEST[prod_inner_id]){
               mysql_query("	UPDATE  `printer_identity`
               SET    `production_id`	= $_REQUEST[printer_model],
               parts_type      = $_REQUEST[part_type],
               parts_category  = $_REQUEST[category],
               amount          = $_REQUEST[amount]
               WHERE
               `id`	= $_REQUEST[prod_inner_id]") or die($error="შეცდომა");;
               break; 
           }

       mysql_query("INSERT INTO `printer_identity`
					(`user_id`, `production_id`, `parts_type`, `parts_category`, `amount`)
				 VALUES
					($user_id, $_REQUEST[printer_model], $_REQUEST[part_type], $_REQUEST[category], $_REQUEST[amount])") or die($error=" არ დაემატა");
      } else{
          $error='ეს პროდუქტი უკვვე დამატებულია ან არაფერი შეგიცვლიათ';
      }      break;        
        
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];

	    $rResult = mysql_query("SELECT 		`PR`.`id`,
											`PR`.`code`,
											`PR`.`name`,
											`UN`.`name`,
											`CAT`.`name`,
											`PR`.`comment`
								FROM 		`production` AS `PR`
								LEFT JOIN 	`production_category` AS `CAT` ON `PR`.`category` = `CAT`.`id`
								LEFT JOIN 	`production_unit` AS `UN`  ON `PR`.`unit` = `UN`.`id`
	    						WHERE		`PR`.`actived` = 1");

		$data = array(
			"aaData"	=> array()
		);

		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}



        break;
        case 'get_list1':
            $count = $_REQUEST['count'];
            $hidden = $_REQUEST['hidden'];
        
            $rResult = mysql_query("SELECT printer_identity.id,	
                printer.`name`,
				printer_parts_type.`name` AS `type`,
				-- parent.`name`,
	    	    production_category.`name` AS `category`											
                FROM	`printer_identity`
                JOIN	`printer_parts_type`	ON `printer_identity`.`parts_type` = `printer_parts_type`.`id`
                JOIN	`production_category`	ON `printer_identity`.`parts_category` = `production_category`.`id`
                -- JOIN  `production_category` AS `parent` on `parent`.`id` = `production_category`.`parent_id`
                JOIN   production ON production.category=production_category.id
                JOIN   production as printer ON printer.id=printer_identity.production_id
                WHERE	production.id=$_REQUEST[id] AND `printer_identity`.`actived` = 1 AND printer_parts_type.actived=1");
        
            $data = array(
                "aaData"	=> array()
            );
        
            while ( $aRow = mysql_fetch_array( $rResult ) )
            {
                $row = array();
                for ( $i = 0 ; $i < $count ; $i++ )
                {
                    /* General output */
                    $row[] = $aRow[$i];
                    if($i == ($count - 1)){
                        $row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
                    }
                }
                $data['aaData'][] = $row;
            }
           break;
    case 'save_prod':
		$prod_id 		= $_REQUEST['id'];

		$arr = array(
				//Main
				'code'				=> htmlspecialchars($_REQUEST['cod'], ENT_QUOTES),
				'part_number'		=> htmlspecialchars($_REQUEST['pn'], ENT_QUOTES),
				'name'				=> htmlspecialchars($_REQUEST['n'], ENT_QUOTES),

				'category'			=> $_REQUEST['cat'],
				'unit'				=> $_REQUEST['un'],
				'country'			=> $_REQUEST['cy'],

				'page_resource'		=> $_REQUEST['pr'],
				'job_circle'		=> $_REQUEST['jc'],
				'min_amount'		=> $_REQUEST['min'],

				'comment'			=> htmlspecialchars($_REQUEST['c'], ENT_QUOTES),
				'image'				=> $_REQUEST['img']
		);

		if($prod_id == ''){
			if(!CheckProductExist($arr['name'])){
				if(!CheckProductCode($arr['code'])){
					AddProduct($user_id, $arr);
				} else {
					$error = 'პროდუქტი ასეთი კოდით უკვე არის სიაში!';
				}
			} else {
				$error = '"' . $arr['name'] . '" უკვე არის სიაში!';
			}
		}else{
			SaveProduct($prod_id, $user_id, $arr);
		}

        break;
    case 'disable':
		$prod_id 		= $_REQUEST['id'];
		DisableProduct($prod_id);

        break;
    case 'delete_image':
		$prod_id 		= $_REQUEST['id'];
		DeleteImage($prod_id);

        break;
    case 'clear':
		$file_list = $_REQUEST['file'];
		ClearProduct();
		if (!empty($file_list)) {
			$file_list = ClearFiles(json_decode($file_list));
		}
		$data = array('file_list' => json_encode($file_list));

        break;
    default:
       $error = "Action is Null";
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Product Catalog Functions
 * ******************************
 */

function ClearProduct() {
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM `production`");

    while( $res = mysql_fetch_assoc($req)){
    	$name = htmlspecialchars($res[name], ENT_QUOTES);
    	mysql_query("	UPDATE
							`production`
						SET
							`name`	= '$name'
						WHERE
							`id`	= $res[id]");
    }
}

function ClearFiles($file_list) {
	$array = array();
	foreach ($file_list as $file) {
		if($file != '0.jpg' && $file != 'index.html'){
			$req = mysql_query("SELECT	`id`
								FROM	`production`
								WHERE	`image` = '$file'");
			if (mysql_num_rows($req) == 0){
				$array[] = $file;
			}
		}
	}
	return $array;
}

function AddProduct($user_id, $arr)
{
	mysql_query("INSERT INTO `production`
					(`user_id`, `code`, `part_number`, `name`, `country`, `category`, `unit`, `min_amount`, `page_resource`, `job_circle`, `image`, `comment`)
				 VALUES
					($user_id, '$arr[code]', '$arr[part_number]',  '$arr[name]', $arr[country], $arr[category], $arr[unit], $arr[min_amount], $arr[page_resource], $arr[job_circle], '$arr[image]', '$arr[comment]')");
}

function SaveProduct($prod_id, $user_id, $arr)
{
	mysql_query("UPDATE
	    			`production`
				 SET
				    `user_id`		= $user_id,
				    `code`			= '$arr[code]',
				    `part_number`	= '$arr[part_number]',
				    `name`			= '$arr[name]',
				    `country`		= $arr[country],
				    `category`		= $arr[category],
				    `unit`			= $arr[unit],
				    `min_amount`	= $arr[min_amount],
				    `page_resource`	= $arr[page_resource],
				    `job_circle`	= $arr[job_circle],
				    `image`			= '$arr[image]',
				    `comment`		= '$arr[comment]'
				 WHERE
					`id`			= $prod_id");
}

function CheckProductExist($prod_name)
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`
										  FROM `production`
										  WHERE `name` = '$prod_name' && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}

function CheckProductCode($code)
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	`id`
										 	FROM	`production`
										  	WHERE	`code` = '$code' && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}

function DisableProduct($prod_id)
{
    if ($_REQUEST[inner]=="true") {
   
     mysql_query("UPDATE    `printer_identity`
                 SET	`actived` = 0
        WHERE	 `id` =  $prod_id ");
        
        return  0;
        ;
    }
	$r=mysql_fetch_array(mysql_query("SELECT 	CONCAT(COUNT(pr.id),production.`name`)
									FROM 	production
									JOIN 	production AS pr on pr.`name`= production.`name`
									WHERE 	production.id=12"));

    mysql_query("UPDATE `production`
				 SET	`actived` = 0, name='old$r[0]'
				 WHERE	`id` = $prod_id ");
}

function DeleteImage($prod_id)
{
	mysql_query("UPDATE
	    			`production`
				 SET
				    `image`			= NULL
				 WHERE
					`id`			= $prod_id");
}

function GetSize($point)
{
	$data = '';
    $req = mysql_query("SELECT `id`, `name`
						FROM `production_unit`");

	if($point == ''){
		$data = '<option value="0" selected="selected"></option>';
	}

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function GetCategory($point)
{
	$data = '';

	$data = '<option value="0" selected="selected"></option>';
	$tree = new CategoryTree($point);
	$data .= $tree->GetData();

	return $data;
}

function GetCountry($point)
{
	$data = '';
    $req = mysql_query("SELECT `id`, `name`
						FROM `country`");

	if($point == ''){
		$data = '<option value="0" selected="selected"></option>';
	}

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function GetProduct($prod_id)
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	`id`,
													`code`,
    												`part_number`,
													`name`,
													`category`,
													`unit`,
    												`country`,
    												`page_resource`,
    												`job_circle`,
													`min_amount`,
													`image`,
    												`comment`
											FROM	`production`
											WHERE	`id` = $prod_id"));
	return $res;
}


function get_part_type($point){
    $data = '';
    $req = mysql_query("SELECT id,`name` FROM printer_parts_type WHERE category = 2 AND actived>0");
    
    if($point == ''){
        $data = '<option value="0" selected="selected"></option>';
    }
    
    while( $res = mysql_fetch_assoc($req)){
        if($res['id'] == $point){
            $data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
        } else {
            $data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
        }
    }
    
    return $data;
    }

function get_printer($point){
    $data = '';
    $req = mysql_query("SELECT DISTINCT production.id, production.`name`
                            FROM `production`
                            JOIN printer_identity ON printer_identity.production_id=production.id
        where production.actived=1 AND printer_identity.actived=1");
    
    if($point == ''){
        $data = '<option value="0" selected="selected"></option>';
    }
    
    while( $res = mysql_fetch_assoc($req)){
        if($res['id'] == $point){
            $data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
        } else {
            $data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
        }
    }
    
    return $data;
}


function GetPage($res = '')
{
    
    
    if ($_REQUEST[inner]=='true') {
        $res=mysql_fetch_array(mysql_query("SELECT 	 amount, production_id, parts_type
                    FROM printer_identity
                     WHERE id=$_REQUEST[id]"));
    //   print_r($res);
    if (!$res[amount]) {
        $res[amount]=1;
    }        
        
         $data = '
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
    		<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="type">პრინტერის მოდელი</label></td>
					<td style="width: 220px; position:fixed; z-index:92">
						<select style="width:220px" id="printer_model" class="idls">' . get_printer($res[production_id]) . '</select>						
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="part_type">ნაწილის ტიპი</label></td>
					<td style="width: 220px; position:fixed; z-index:91">
						<select style="width:220px" id="part_type" class="idls">' . get_part_type($res[parts_type]) . 
						'</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="amount">რაოდენობა</label></td>
					<td>
						<input type="number" id="amount" class="idle num" 
						  onkeypress="{if (event.which != 8 & event.which != 0 & event.which!=46 & (event.which < 48 || event.which > 57)) {$(\'#errmsg\').html(\'მხოლოდ რიცხვი\').show().fadeOut(\'slow\'); return false;}}" class="idle num"  value="' . $res[amount] . '" />
					    <span id="errmsg" style="color: red; display: none;">მხოლოდ რიცხვი</span>
					</td>
				</tr>	
			</table>
        </fieldset>
				<!-- ID -->
		<input type="hidden" id="prod_inner_id" value="' . $_REQUEST['id'] . '" />				      
    </div>
    ';
    return $data;
    }
    
	$image = $res[image];
	if(empty($image)){
		$image = '0.jpg';
	}
	$data = '
	<div id="dialog-form">
		<fieldset style="width: 350px; float: left;">
	    	<legend>ძირითადი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
	    		<tr>
					<td style="width: 170px;"><label for="code">კოდი</label></td>
					<td>
						<input type="text" id="code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['code'] . '" />
					</td>
				</tr>
	    		<tr>
					<td style="width: 170px;"><label for="part_number">Part Number</label></td>
					<td>
						<input type="text" id="part_number" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['part_number'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="name">დასახელება</label></td>
					<td>
						<input type="text" id="name" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['name'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">კატეგორია</label></td>
					<td>
						<select id="category" class="idls">' . GetCategory($res[category]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">ზომის ერთეული</label></td>
					<td>
						<select id="unit" class="idls num">' . GetSize($res[unit]) . '</select>
					</td>
				</tr>
			</table>
        </fieldset>
 	    <fieldset style="width: 350px; float: right;">
	    	<legend>პროდუქტის სურათი</legend>

	    	<table class="dialog-form-table" width="100%">
	    		<tr>
					<td id="img_colum" colspan="2">
						<img id="upload_img" src="media/uploads/images/production/' . $image . '">
					</td>
				</tr>
				<tr><!-- Upload Image -->
					<td id="act">
						<span>
							<a href="#" id="view_image" class="complate">View</a> | <a href="#" id="delete_image" class="delete">Delete</a>
						</span>
					</td>
					<td>
						<div class="file-uploader">
							<input id="choose_file" type="file" name="choose_file" class="input" style="display: none;">
							<button id="choose_button" class="center">აირჩიეთ ფაილი</button>
						</div>
					</td>
				</tr>
			</table>
        </fieldset>
		<div class="clear"></div>
		<fieldset style="width: 350px; float: left;">
	    	<legend>დამატებითი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="country">ქვეყანა</label></td>
					<td>
						<select id="country" class="idls">' . GetCountry($res[country]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="page_resource">გვერდების რესურსი</label></td>
					<td>
						<input type="text" id="page_resource" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['page_resource'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="job_circle">სამუშაო ციკლი</label></td>
					<td>
						<input type="text" id="job_circle" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['job_circle'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="min_amount">მინ. რაოდენობა</label></td>
					<td>
						<input type="text" id="min_amount" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['min_amount'] . '" />
					</td>
				</tr>
			</table>
        </fieldset>
		<fieldset style="width: 350px; float: right;">
	    	<legend>შენიშვნა</legend>

	    	<table class="dialog-form-table" style="height: 120px;">
				<tr>
					<td valign="top">
						<textarea id="comment" class="idle large" cols="40" rows="6">' . $res['comment'] . '</textarea>
					</td>
				</tr>
			</table>
        </fieldset>
		<fieldset>
	          <legend>თავსებადობა</legend>	        
			    <div class="inner-table">
				    <div id="dt_example" class="ex_highlight_row">
				        <div id="container" class="overhead_container">
				        	<div id="button_area" class="inner_buttons">
						    <button id="add_button_inner">დამატება</button>
						    <button id="delete_button_inner">წაშლა</button>						    				
							</div>
				            <div id="dynamic">
				                <table class="display" id="inner_table">
                                    <thead>
                                        <tr id="datatable_header">
                                            <th>ID</th>
	                                        <th style="width: 33%;">პრინტერის მოდელი</th> 
                                            <th style="width: 33%;">ნაწილის ტიპი</th>       
                                            <th style="width: 34%">ნაწილი</th> 
						                    <th style="width: 30px">#</th>                                      
                                        </tr>
                                    </thead>
                                    <thead>
                                        <tr class="search_header">
                                            <th class="colum_hidden">
                                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
                                            </th>
                                            <th>
                                                <input type="text" name="search_type" value="ფილტრი" class="search_init"  />
                                            </th>
                                            <th>
                                                <input type="text" name="search_type" value="ფილტრი" class="search_init"  />
                                            </th>                
                                            <th>
                                                <input type="text" name="search_type" value="ფილტრი" class="search_init" />
                                            </th>
						                    <th>&nbsp;</th>  
                                        </tr>
                                    </thead>                       
                                    <tfoot>
                                        <tr>
                                            <th>&nbsp;</th>
	                                        <th>&nbsp;</th>    
                                            <th>&nbsp;</th>
                                            <th>&nbsp;</th>
						                    <th>&nbsp;</th>    
                                        </tr>
                                    </tfoot>
				                </table>
				            </div>
				        </div>
				    </div>
				</div>
			</fieldset>				    
		<!-- ID -->
		<input type="hidden" id="prod_id" value="' . $_REQUEST['id'] . '" />
    </div>

    ';
	return $data;
}

?>